﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Threading;
using System.Timers;
using System.Web;
using BusinessEntity;
using BusinessLogic;

namespace CentalineWeb.Common
{
    public class WorkTimer
    {
        private System.Timers.Timer _timer;
        private string _workorder;
        /// <summary>
        /// 提交报修若干分钟后，自动分派工单
        /// </summary>
        /// <param name="workorder"></param>
        public void NewTimer(string workorder ,int timeCount)
        {
            this._workorder = workorder;
            _timer = new System.Timers.Timer(timeCount);
            _timer.Elapsed += OnTimeEvent;
            _timer.Enabled = true;
            _timer.Start();
        }

        private  void OnTimeEvent(object sender, ElapsedEventArgs e)
        {
            _timer.Stop();
            //如果不为未分配状态则不再自动分配
            var worker = new RepairManager().GetByOrder(_workorder);
            if (worker.StatusId!=null&&worker.StatusId.StatusId != 1)
            {
                _timer.Stop();
                return;
            }
            AutoAsign(_workorder);
        }

        public void AutoAsign(string workorder)
        {
            var fitestuserid = new UserManager().GetFitestUserIdByWorkOrder(workorder);
            var user = new UserManager().GetUserById(fitestuserid);
            new RepairManager().AsignOrder(workorder, fitestuserid);
            var model = new SheetHistory()
            {
                OpDate = DateTime.Now,
                OperId = new UserManager().GetIdByUserId("system"),
                OpId = (int)(BusinessEntity.Operation.AcceptSheet),
                Remark = "工单自动分配给" + user.FullName,
                SheetId = new RepairManager().GetIdByWorkId(workorder)
            };
            new SheetHistoryManager().AddOne(model);
            var row = new VwManager().GetOneByOrder(workorder);
            MailPush.SendMail("中原电脑报修平台工单分配通知", string.Format("<html><body>工单号：{7}<br />报修人员：{0}<br />报修时间：{1}<br />所在分行：{2}<br />电脑编号：{6}<br />问题种类：{3}<br />故障描述：{4}<br />联系电话:{5}</body></html>", row["applyemp"], row["applytime"], row["deptname"], row["troubledesc"], row["troubledesc2"], row["phone"], row["compid"], workorder), row["fixeremail"].ToString());
            MailPush.SendMail("您的工单已受理", string.Format("工单号：{0}<br />维修人员：{1}",workorder,row["repemp"]), row["email"].ToString());
        }
    }
}